#!/bin/bash
###############################################################################
#
# Title: Post Script for Salt Installation
# Authors: Shane Lee
# Date: December 2015
#
# Description: This script copies the minion config file and starts the salt
#              service
#
# Requirements:
#    - None
#
# Usage:
#     This script is run as a part of the OSX Salt Installation
#
###############################################################################
echo "Post install started on:" > /tmp/postinstall.txt
date >> /tmp/postinstall.txt
trap 'quit_on_error $LINENO $BASH_COMMAND' ERR

quit_on_error() {
    echo "$(basename $0) caught error on line : $1 command was: $2" >> /tmp/postinstall.txt
    exit -1
}

###############################################################################
# Check for existing minion config, copy if it doesn't exist
###############################################################################
if [ ! -f /etc/salt/minion ]; then
    echo "Config copy: Started..." >> /tmp/postinstall.txt
    cp /etc/salt/minion.dist /etc/salt/minion
    echo "Config copy: Successful" >> /tmp/postinstall.txt
fi

###############################################################################
# Register Salt as a service
###############################################################################
echo "Service start: Started..." >> /tmp/postinstall.txt
# launchctl load "/Library/LaunchDaemons/com.saltstack.salt.minion.plist"
echo "Service start: Enabling service..." >> /tmp/postinstall.txt
launchctl enable system/com.saltstack.salt.minion
echo "Service start: Bootstrapping service..." >> /tmp/postinstall.txt
launchctl bootstrap system /Library/LaunchDaemons/com.saltstack.salt.minion.plist

if /bin/launchctl list "com.saltstack.salt.minion" &> /dev/null; then
    echo "Service is running" >> /tmp/postinstall.txt
else

    echo "Service start: Kickstarting service..." >> /tmp/postinstall.txt
    launchctl kickstart -kp system/com.saltstack.salt.minion
fi

echo "Service start: Successful" >> /tmp/postinstall.txt

echo "Service disable: Disabling Master, Syndic, and API" >> /tmp/postinstall.txt

launchctl disable system/com.saltstack.salt.master
launchctl disable system/com.saltstack.salt.syndic
launchctl disable system/com.saltstack.salt.api

# echo "Path: Adding salt to the path..." >> /tmp/postinstall.txt
# echo "/opt/salt/bin" > /etc/paths.d/salt

echo "Post install completed successfully" >> /tmp/postinstall.txt

exit 0
